class Solution {
public:
    bool flag = false;
    unordered_map<char, unordered_set<char>> hash;
    unordered_map<char, int> sign;
    string alienOrder(vector<string>& words) {

        for (int i = 0; i < words.size(); i++)
            for (auto& ch : words[i])
                sign[ch] = 0;
        for (int i = 0; i < words.size(); i++) {
            for (int j = i + 1; j < words.size(); j++) {
                fun(words[i], words[j]);
                if (flag)
                    return "";
            }
        }
        string ret;
        queue<char> q;
        for (auto& [a, b] : sign)
            if (b == 0)
                q.push(a);
        while (!q.empty()) {
            char front = q.front();
            q.pop();
            ret.push_back(front);
            for (auto& ch : hash[front]) {
                sign[ch]--;
                if (!sign[ch])
                    q.push(ch);
            }
        }
        for (auto& [a, b] : sign) {
            if (b != 0)
                return "";
        }
        return ret;
    }
    void fun(string& num1, string& num2) {
        int size = min(num1.size(), num2.size());
        int k = 0, s = 0;
        for (; k < size; k++) {
            char x = num1[k], y = num2[k];
            if (x != y) {
                if (!hash.count(x) || !hash[x].count(y)) {

                    hash[x].insert(y);
                    sign[y]++;
                }
                break;
            }
        }
        if (k == num2.size() && k < num1.size())
            flag = true;
    }
};